<?php
namespace app\client\controller;
use app\common\lib\Redis;

class Near extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    public function person() {
        $params = request()->get();
        
        $lng = isset($params['longitude']) ? floatval($params['longitude']) : 114.085947;
        $lat = isset($params['latitude']) ? floatval($params['latitude']) : 22.547;
        
        unset($params);
        
        $redis = new Redis();
        
        $geos = $redis->handler()->geoRadius('near_person', $lng, $lat, 3000 ,'m' , ['ASC', 'WITHDIST', 'WITHCOORD', 'COUNT' => 20]);

        $userKeys = [];
        foreach ($geos as $geo) {
            array_push($userKeys, redisUserKey($geo[0]));
        }
        
        $list = [];
        $userList = $redis->mget($userKeys);
        $redis->close();
        
        if(!empty($userList)) {
            foreach ($userList as $k => $user) {
                if(!empty($user)) {
                    array_push($list, ['location' => $geos[$k][2], 'user' => $user]);
                }
            }
        }
        
        return successResult(['list' => $list]);
    }
    
    public function hiddeLocation() {
        try {
            $redis = new Redis();
            $rs = $redis->handler()->zRem('near_person', $this->userid);
            $redis->close();
        } catch (\Exception $e) {
            return errorResult();
        }

        return successResult();
    }
    
    public function updateLocation() {
        $params = request()->post();
        
        $lng = isset($params['longitude']) ? floatval($params['longitude']) : 0;
        $lat = isset($params['latitude']) ? floatval($params['latitude']) : 0;
        if(empty($lng) || empty($lat)) {
            return errorResult();
        }
        
        $redis = new Redis();
        $redis->geoadd('near_person', $lng, $lat, $this->userid);
        
        return successResult();
    }
}